import { uuid, debounce } from '../utils'

const updateOutput = (data: any, output: any) => {
  output.get()?.forEach?.((port: any) => {
    const pick = data.picks.find(({ key }) => key == port.id)
    if (!pick) {
      output.remove(port.id)
    } else {
      port.setTitle(pick.property)
    }
  })
  data.picks?.forEach?.((item) => {
    const { key, property } = item
    if (!output.get(key)) {
      const addOption = {
        id: key,
        title: property,
        schema: data.inputSchema,
        editable: false,
        deletable: false
      }
      console.log('addOption = ', addOption)
      output.add(addOption)
    }
  })
}
const createItem = () => {
  const uid = uuid()
  return {
    key: uid,
    property: `value`,
    value: null
  }
}
export default {
  '@inputConnected'({ data, output }, fromPin: any) {
    data.inputSchema = fromPin.schema
    if (!Array.isArray(data.picks)) {
      data.picks = []
    }
    if (data.picks.length < 1) {
      data.picks.push(createItem())
    }
    updateOutput(data, output)
  },
  ':root': ({ data }: any, cate1: any) => {
    cate1.title = '取数配置'
    cate1.items = [
      {
        title: '数据列表',
        type: 'array',
        options: {
          getTitle: ({ property }) => {
            return property
          },
          onAdd: createItem,
          items: [
            {
              title: '常量名称',
              type: 'text',
              value: 'property'
            },
            {
              title: '常量值',
              type: 'valueSelect',
              options: ['text', 'number', 'boolean'],
              value: 'value'
            }
          ]
        },
        value: {
          get({ data }: any) {
            return data.picks || []
          },
          set({ data, output }: any, options: any[]) {
            data.picks = options
            updateOutput(data, output)
          }
        }
      }
    ]
  }
}
